package com.duojuhe.redis.redisson.config;


import com.duojuhe.redis.redisson.RedisSonLockUtils;
import com.duojuhe.redis.redisson.impl.DistributedLockerImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 分布式锁配置，支持redis哨兵模式，集群模式的单机模式，当前我们配置的是单机模式
 */
@Slf4j
@Configuration
public class RedisSonConfig {
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private String port;
    @Value("${spring.redis.password}")
    private String password;

    @Bean
    public RedissonClient redissonClient(){
        try {
            Config config = new Config();
            //单节点
            //redisSon版本是3.5，ip前面要加上“redis://”，不然会报错，3.2版本可不加
            config.useSingleServer().setAddress("redis://" + host + ":" + port);
            if (StringUtils.isBlank(password)) {
                config.useSingleServer().setPassword(null);
            } else {
                config.useSingleServer().setPassword(password);
            }
            return Redisson.create(config);
        }catch (RuntimeException e){
            log.error("Redis连接失败：",e);
            throw new RuntimeException("Redis连接失败");
        }
    }

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redissonClient) {
        return new RedissonConnectionFactory(redissonClient);
    }

    /**
     * 分布式锁实例化并交给工具类
     * @param redissonClient
     */
    @Bean
    public DistributedLockerImpl redissonLocker(RedissonClient redissonClient) {
        DistributedLockerImpl locker = new DistributedLockerImpl(redissonClient);
        RedisSonLockUtils.setLocker(locker);
        return locker;
    }
}
